package cn.uc.ucgc.community.upgrade.conf.task;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.uc.ucgc.community.upgrade.Constants;
import cn.uc.ucgc.community.upgrade.Task;
import cn.uc.ucgc.community.upgrade.Utils;
import cn.uc.ucgc.community.upgrade.conf.FullReplaceJob;

/**
 * 文件做全量覆盖任务
 * 
 * @author yuyj@ucweb.com
 * @createDate 2014-3-13
 *
 */
public class FullReplaceTask extends Task {
    private static final Logger logger = LoggerFactory.getLogger(FullReplaceTask.class);
    //需要做全量替换的任务
    private List<FullReplaceJob> jobs;

    public FullReplaceTask(List<FullReplaceJob> needDoJobs) {
        super.setTaskDesc("Full Replace File Task");
        jobs = needDoJobs;
    }

    @Override
    public void doTask(StringBuilder sb) throws Exception {
        if (null == jobs || jobs.isEmpty()) {
            sb.append(Constants.TASK_RESULT_NOTASK_SUFFIX);
            return;
        }

        //如果有准备任务，执行之
        logger.warn("Need full replace config file count:{}", jobs.size());
        //一次执行任务
        for (FullReplaceJob job : jobs) {
            if (null == job) {
                continue;
            }
            //1)初始化任务时，就判断好对应的文件是否存在，此处不再做校验
            //2)此处就直接读取原文件内容，写入目的文件中
            File srcPath = job.getSrcPath();
            File dstPath = job.getDstPath();
            
            logger.info("copy from:{} to:{}", srcPath.getCanonicalPath(),
                    dstPath.getCanonicalPath());
            //这里需要通过最原始的二进制方式完成升级操作
            BufferedInputStream bR = null;
            BufferedOutputStream bW = null;
            try {
                bR = new BufferedInputStream(new FileInputStream(srcPath));
                bW = new BufferedOutputStream(new FileOutputStream(dstPath));
                byte[] tmpByte = new byte[1024];
                int cnt = bR.read(tmpByte);
                while (-1 != cnt) {
                    bW.write(tmpByte, 0, cnt);
                    cnt = bR.read(tmpByte);
                }
                bW.flush();
            } finally {
                Utils.closeFileStream(bR);
                Utils.closeFileStream(bW);
            }
        }
    }

}
